from dotenv import load_dotenv
from openai import OpenAI

import time

load_dotenv()
#
client = OpenAI()


def submit_message_wait_completion(assistant_id, thread_id, user_message, file_ids=None):
    for run in client.beta.threads.runs.list(thread_id=thread_id):
        if run.status == 'in_progress':
            print(f"等待Run {run.id} 完成...")
            while True:
                run_status = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id).status
                if run_status in ["successed", "failed"]:
                    break
                time.sleep(5)

    params = {
        'thread_id': thread_id,
        'role': "user",
        'content': user_message
    }

    if file_ids:

        attachments = []

        for file_id in file_ids:
            attachment = {

                "file_id": file_id,
                "tools": [
                    {
                        "type": "code_interpreter"
                    }
                ]
            }

            attachments.append(attachment)
            params['attachments'] = attachments



    client.beta.threads.messages.create(**params)
    run = client.beta.threads.runs.create(thread_id=thread_id, assistant_id=assistant_id)

    return run 





# submit_message_wait_completion('asst_8yPASzS0kYIbwIi0xj4r2Nad' ,
#                                'thread_a7nVoRPoHusmhbFzLTmAMnnb',
#                                '请根据刚才创建的图表，帮我总结2句话，每句话字数限制在30字以内，这将用于ppt展示' )



def get_resp (thread_id):
    return client.beta.threads.messages.list(thread_id=thread_id)



resp = get_resp('thread_a7nVoRPoHusmhbFzLTmAMnnb')

content = resp.data[0].content[0].text.value

print(content)